#include "app_mqtt.h"
#include "MQTTClient.h"
#include "log/log.h"
#include "string.h"

static MQTTClient client;
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
static MQTTClient_message pubmsg = MQTTClient_message_initializer;

// 定义接收处理消息数据的回调函数指针

static int (*recv_callback)(char *) = NULL;

// 当消息发送完成时，调用此函数
void delivered(void *context, MQTTClient_deliveryToken dt)
{
    // 打印调试信息，表示消息发送完成
    log_debug("发送消息完成");
}

// 此函数 返回1代表接收处理函数成功，返回0代表接收处理函数失败
int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    int result = 0; // 默认失败
    if (recv_callback != NULL)
    {
        result = (recv_callback((char *)message->payload) == 0) ? 1 : 0;
    }
    // 释放消息
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return result;
}

void connlost(void *context, char *cause)
{
    log_error("连接丢失原因：%s", cause);
}
int app_mqtt_init(void)
{
    // 创建 mqtt客户端
    int result;
    if ((result = MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_create failed");
        return -1;
    }
    // 设置回调函数
    if ((result = MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered) != MQTTCLIENT_SUCCESS))
    {
        log_error("MQTTClient_setCallbacks failed");
        MQTTClient_destroy(&client);
        return -1;
    }

    // 连接mqtt服务器
    if ((result = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_connect failed");
        MQTTClient_destroy(&client);
        return -1;
    }
    // 订阅主题(PULL)
    if ((MQTTClient_subscribe(client, TOPIC_PULL, QOS) != MQTTCLIENT_SUCCESS))
    {
        log_error("MQTTClient_subscribe failed");
        MQTTClient_disconnect(client, TIMEOUT);

        MQTTClient_destroy(&client);
        return -1;
    }
    return 0;
}

void app_mqtt_close(void)
{
    MQTTClient_unsubscribe(client, TOPIC_PULL);
    MQTTClient_disconnect(client, TIMEOUT);
    MQTTClient_destroy(&client);
}

int app_mqtt_send(char *json)
{
    pubmsg.payload = json;
    pubmsg.payloadlen = strlen(json);
    pubmsg.qos = QOS;

    if (MQTTClient_publishMessage(client, TOPIC_PUSH, &pubmsg, NULL) != MQTTCLIENT_SUCCESS)
    {
        log_error("MQTTClient_publishMessage failed");
        return -1;
    }
    return 0;
}

// 写法1
//  typedef int (*Callback)(char *);
//  void app_mqtt_registerRecvCallback(Callback callback)
//  {

//     recv_callback = callback;
// }

void app_mqtt_registerRecvCallback(int (*callback)(char *json))
{

    recv_callback = callback;
}
